#include "client.h"
#include <iostream>
using namespace std;

Client::Client(QObject * parent): QTcpSocket(parent)
{
    connect(this, SIGNAL(connected()), this, SLOT(slotConnected()));
    connect(this, SIGNAL(readyRead()), this, SLOT(dataRecive()));
}

void Client::slotConnectServer(QString name, QString IP, QString port)
{
    userName = name;
    serverIP = new QHostAddress(IP);
    serverPort = port.toInt();
    //连接服务器，注意serverIP是QHostAddress的指针
    connectToHost(*serverIP, serverPort);
}

void Client::slotSendServer(QString msg)
{
    QString sendMsg = userName + ": " + msg;
    write(sendMsg.toLatin1());
}

void Client::slotDisconnectServer()
{
    write(QString(userName + " leave the chat room").toLatin1());
    disconnectFromHost();
}

void Client::slotConnected()
{
//    cout<<"got it!"<<endl;
    QString enterMsg = userName + " enter the chat room";
    write(enterMsg.toLatin1());
}

void Client::dataRecive()
{
    while(bytesAvailable() > 0)
    {
        int length = bytesAvailable();
        char buf[1024];
        read(buf, length);
        QString msg = buf;
        emit updateClientUI(msg, length);
    }
}
